package com.xiaoze.springcloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.Arrays;

/**
 * @author xiaoze
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 将客户端的信息存储在内存中,内存模式
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
//        if (ArrayUtils.isNotEmpty(clientLoadProperties.getClients())) {
//            for (ClientProperties config : clientLoadProperties.getClients()) {
//                builder
//                        //设置客户端和密码
//                        .withClient(config.getClientId()).secret(config.getClientSecret())
//                        //设置token有效期
//                        .accessTokenValiditySeconds(7 * 24 * 3600)
//                        //设置refreshToken有效期
//                        .refreshTokenValiditySeconds(7 * 24 * 3600)
//                          // 单点登录时配置
//                          .redirectUris("http://localhost:9501/login")
//                        //支持的认证方式
//                        .authorizedGrantTypes("refresh_token", "authorization_code", "password").autoApprove(false)
//                        //授权域
//                        .scopes("app","write");
//            }
//        }

        //设置客户端和密码
        builder.withClient("main-operation").secret("123456")
                // 设置token有效期  2小时
                .accessTokenValiditySeconds(60 * 60 * 2)
                // 设置refreshToken有效期  7天
                .refreshTokenValiditySeconds(60 * 60 * 24 * 7)
                // 自动授权配置
                .autoApprove(true)
                // 配置申请的权限范围
                .scopes("all")
                //加上验证回调地址
                .redirectUris("http://baidu.com")
                // 配置grant_type,表示授权类型
                .authorizedGrantTypes("authorization_code", "password", "refresh_token", "client_credentials");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

        // 将增强的token设置到增强链中
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer(), jwtAccessTokenConverter()));

        endpoints.tokenStore(tokenStore())
                 .accessTokenConverter(jwtAccessTokenConverter())
                 .userDetailsService(userDetailsService)
                 .tokenEnhancer(tokenEnhancerChain)
                 .authenticationManager(authenticationManager);
    }

    /**
     * 定义令牌端点上的安全性约束
     *
     * 必须设置allowFormAuthenticationForClients 否则没有办法用postman获取token
     * 也需要指定密码加密方式BCryptPasswordEncoder
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        // permitAll()公开获取token的url，获取密钥不需要需要身份认证（isAuthenticated()则需要）
        oauthServer.tokenKeyAccess("denyAll()")
                   // 校验token的合法性
                   .checkTokenAccess("permitAll()")
                   // 支持把secret和clientId写在url上，否则需要在头上
                   .allowFormAuthenticationForClients()
                   .passwordEncoder(myPasswordEncoder);
    }

    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Bean
    protected JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenEnhancer customTokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("auth-operation.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("auth-operation", "123456".toCharArray());
    }

}
